//
//  LQComposeViewController.swift
//  Weibo
//
//  Created by ios on 16/8/16.
//  Copyright © 2016年 ios. All rights reserved.
//

import UIKit
import SVProgressHUD
class LQComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

//        self.view.backgroundColor = UIColor.darkGrayColor()
        setupUI()
    }
    //  MARK:   - 懒加载控件
    //  右边按钮
    private lazy var rightButton: UIButton = {
       let button = UIButton()
        //设置点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        //设置title
        button.setTitle("发送", forState: .Normal)
        //设置字体
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        //设置不同状态的文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
          //  设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState:.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //  设置大小
        button.size = CGSize(width: 45, height: 30)
        return button
    }()
    
    //设置标题视图
    private lazy var titleView:UILabel = {
        let label = UILabel()
        //设置字体大小和颜色
        label.textColor = UIColor.darkGrayColor()
        label.font = UIFont.systemFontOfSize(17)
        
        //设置文字
        if let name = LQUserAccountViewModel.shareUserAccount.userAccount?.name {

            let result = "发微博\n\(name)"
            //  获取名称的range
            let range = (result as NSString).rangeOfString(name)
            
            let attributedStr = NSMutableAttributedString(string: result)
            //添加副文本属性
            attributedStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(14)], range: range)
            label.attributedText = attributedStr
        }
        //  多行显示t
        label.numberOfLines = 0
        label.textAlignment = .Center 
        label.sizeToFit()
        return label
    }()
    
    //发微博视图
    private lazy var textView: LQComposeTextView = {
        let View = LQComposeTextView()
        View.placeHolder = "东京不太热"
        View.delegate = self
        View.font = UIFont.systemFontOfSize(16)
        //  垂直方向开启拖动
        View.alwaysBounceVertical = true
         //  扩展 不想要纠错工具条的显示
        View.autocorrectionType = .Yes
        return View
    }()
    
    //底部的toolbar
    private lazy var toolBar:LQComposeToolBar = {
        let  composeToolbar  = LQComposeToolBar(frame:  CGRectZero)
        composeToolbar.backgroundColor = UIColor.darkGrayColor()
        return composeToolbar
    }()
    
    //配图
    private lazy var pictureView:LQComposePictureView = {
        let picView = LQComposePictureView()
        picView.backgroundColor = self.textView.backgroundColor
        return picView
    
    }()
    //表情键盘
    private lazy var EmoticonKeyBoard:LQEmoticonKeyBoard = {
      let view = LQEmoticonKeyBoard()
        
        //  指定表情键盘大小
      view.size = CGSize(width: self.textView.width, height: 216)
      return view
    }()
    
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        //监听键盘改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
     //设置导航栏视图
        setnavUI()
     //添加控件
    view.addSubview(textView)
    view.addSubview(toolBar)
    textView.addSubview(pictureView)
        
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }

        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        
        toolBar.didSelecteToolBarButtonClosure = { [weak self] (type: LQComposeToolBarButtonType) in

            //  根据点击按钮的枚举值进行判断
            switch type {
                
            case .Picture:
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                self?.didSelectedEmoticon()
            case .Add:
                print("加号")

        }
            
                
}
        //  设置配图点击加号的闭包
        pictureView.didSeletedAddImg = { [weak self] in
            self?.didSelectedPicture()
        }
    
        
}
    //设置导航栏视图
    private func setnavUI(){
        //左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        //右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //设置右侧按钮不可用 自定义的customView按钮只能在这里设置
        navigationItem.rightBarButtonItem?.enabled = false
        
        //  设置导航栏的自定义titleView
        
        navigationItem.titleView = titleView
    }
    
       //MARK: --点击取消按钮
    @objc private func cancelAction(){
        //取消第一响应者
        self.view.endEditing(true)
     dismissViewControllerAnimated(true, completion: nil)
    
    }
    
     //MARK: --点击发送按钮
    @objc private func sendAction(){
        //  获取微博内容
        let status = textView.text!
        //  获取accesstoken
        let accessToken = LQUserAccountViewModel.shareUserAccount.accessToken!
        //  获取图片
        let image = pictureView.images.first!
         SVProgressHUD.show()
        if pictureView.images.count > 0 {
             //  请求发送微博文字和图片接口
            LQAFNetworkingTools.sharedTools.upadate(accessToken, status: status, image: image, callBack: { (response, error) -> () in
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络异常发送失败")
                    return
                }else{
                    
                    SVProgressHUD.showErrorWithStatus("发送成功")
                }
            })
        }else{
            // 请求发送微博文字
        LQAFNetworkingTools.sharedTools.update(accessToken, status: status) { (response, error) -> () in
            if error != nil {
              SVProgressHUD.showErrorWithStatus("网络异常发送失败")
              return
            }else{
            
              SVProgressHUD.showErrorWithStatus("发送成功")
            }
        }
    }
}
    
     //  MARK:   - 监听键盘改变的通知方法
   @objc private func keyboardFrameChange(noti: NSNotification){
    //  获取键盘的frame
    let keyBoardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
    
    //  获取动画时长
    let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
    
    //  更新约束
    toolBar.snp_updateConstraints { (make) -> Void in
        make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - self.view.height)

    }
    
    //  更新约束动画
//    UIView.animateWithDuration(duration) { () -> Void in
//        self.view.layoutIfNeeded()
//
//    }
    UIView.animateWithDuration(duration) { () -> Void in
        self.view.layoutIfNeeded()
    }
}
    
}
//  MARK:   点击toolbar按钮处理逻辑
extension LQComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
  //处理点击表情按钮逻辑
    func didSelectedEmoticon(){
        if textView.inputView == nil {
            //  设置自定义表情键盘
         textView.inputView = EmoticonKeyBoard
         toolBar.switchEmotionIcon(true)
        }else{
            //  设置为系统键盘
          textView.inputView = nil
          toolBar.switchEmotionIcon(false)
        }
        //设置其为第一响应者
        textView.becomeFirstResponder()
        // 重写刷新inputview
        textView.reloadInputViews()
        
    }
    
  //处理点击图片逻辑
    func didSelectedPicture(){
        let picStr = UIImagePickerController()
        picStr.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            //  设置来源类型
            picStr.sourceType = .Camera
            
        } else {
            //  设置图库
            picStr.sourceType = .PhotoLibrary
        }
        
        //  判断前置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            
          
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            
        } else {
           
        }
        
        presentViewController(picStr, animated: true, completion: nil)

    }

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        let ScaleImg = image.scaleImageWithScaleWidth(200)
        //  添加配图信息
        pictureView.addImage(ScaleImg)
          picker.dismissViewControllerAnimated(true, completion: nil)
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
          picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    }


//  MARK:   -实现UITextViewDelegate代理方法
extension LQComposeViewController: UITextViewDelegate {
  //内容改变
    func textViewDidChange(textView: UITextView) {
        //  如果有内容则右侧按钮可用,否则不可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    //  将要拖动的时候让其失去第一响应者
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        //  失去第一响应者
        self.view.endEditing(true)
    }



}














